package ThreadDemo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-29
 * Time: 19:15
 */
public class ReentrantLockTest {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        //创建ReentrantLock锁
        ReentrantLock rLock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            //加锁

            try{
                for (int i = 0; i < 5000; i++) {
                    rLock.lock();
                    count++;
                }
            }finally {
                //解锁
                rLock.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            //加锁
            try{
                for (int i = 0; i < 5000; i++) {
                    rLock.lock();
                    count++;
                }
            }finally {
                //解锁
                rLock.unlock();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + count);
    }
}
